package pers.cyril.jdb.sql.parser;

import lombok.Data;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.update.Update;
import pers.cyril.jdb.storage.api.ExecuteResult;

/**
 * 说点什么吧
 *
 * @author Wang Cyril
 * @date 2024/5/23 21:17
 */
@Data
public class SQLStatement {

    public static enum StatementType {
        SELECT, INSERT, UPDATE, DELETE;
    }

    private StatementType type;
    private Statement statement;
    private boolean valid;
    private String error;

    public SQLStatement(String sql) {
        this.parse(sql);
    }

    public void parse(String sql) {
        try {
            Statement statement = CCJSqlParserUtil.parse(sql);
            this.setStatement(statement);
            this.setValid(true);
            if (statement instanceof Select) {
                this.setType(SQLStatement.StatementType.SELECT);
            } else if (statement instanceof Insert) {
                this.setType(SQLStatement.StatementType.INSERT);
            } else if (statement instanceof Update) {
                this.setType(SQLStatement.StatementType.UPDATE);
            } else if (statement instanceof Delete) {
                this.setType(SQLStatement.StatementType.DELETE);
            } else {
                this.setValid(false);
                this.setError("unsupport sql statement type");
                this.setStatement(null);
            }
        } catch (JSQLParserException e) {
            this.setValid(false);
            this.setError(e.getMessage());
        }

    }

    public ExecuteResult execute() {
        ExecuteResult result = null;
        switch (this.type) {
            case SELECT:
                break;
            case INSERT:
                break;
            case UPDATE:
                break;
            case DELETE:
                break;
            default:
                break;
        }
        return result;
    }

    public static void main(String[] args) {
        SQLStatement sqlStatement = new SQLStatement("select a.a1 from table1 a where a.a1 > 1");
        System.out.println(sqlStatement);
    }
}
